<template>
  <el-dialog
    :title="type === 'add' ? '新增角色' : '修改角色'"
    width="30%"
    top="30vh"
    :visible.sync="isShow"
    @close="_onCancel(false)"
  >
    <el-form ref="myRoleForm" :model="roleForm" label-width="80px">
      <el-form-item label="角色名称:">
        <el-input v-model="roleForm.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色描述:">
        <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="roleForm.description"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="_onSave">保 存</el-button>
      <el-button @click="_onCancel(false)">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { editTheRole, addRole } from "@/http/rootSetApi.js";
export default {
  props: {
    type: {
      type: String,
      required: true
    },
    choiceData: {
      type: null || Object
    }
  },
  data() {
    return {
      isShow: true,
      roleForm: {
        name: "",
        description: "",
        id: "",
        data: []
      }
    };
  },
  methods: {
    // 保存
    _onSave() {
      this.$confirm("是否继续此操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (this.type == "add") {
            addRole(this.roleForm.name, this.roleForm.description)
              .then(() => {
                this.$message.success("添加成功");
                this._onCancel("add", this.roleForm);
              })
              .catch(() => {
                this.$message.error("添加失败!!!");
              });
          } else if (this.type == "edit") {
            editTheRole(this.roleForm)
              .then(() => {
                this._onCancel("edit");
                this.$message.success("修改成功！！！");
              })
              .catch(() => {
                this.$message.error("修改失败!!!");
              });
          }
        })
        .catch(() => {});
    },

    // 关闭
    _onCancel(type, form = null) {
      this.$emit("onCancel", { type, form });
    }
  },
  created() {
    if (this.choiceData !== null) {
      console.log(this.choiceData);
      this.roleForm = this.choiceData;
    }
  }
};
</script>